#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#include<unistd.h>
#include<arpa/inet.h>
#include<sys/socket.h>

void error_handing(char *message)
{
    fputs(message,stderr);
    fputc('\n',stderr);
    exit(1);
}

int main(int argc, char const *argv[])
{
    //步骤1：创建套接字
    int client_sock;
    client_sock = socket(PF_INET,SOCK_STREAM,0);
    if (client_sock == -1)
    {
        error_handing("socket() error");
    }
    
    //步骤2：连接端口
    struct sockaddr_in connect_addr;
    connect_addr.sin_family = AF_INET;
    connect_addr.sin_addr.s_addr = inet_addr("127.0.0.1");
    connect_addr.sin_port = htons(3333);

    //connect时操作系统内核分配主机ip作为ip地址，随机端口作为访问端口
    if (connect(client_sock,(struct sockaddr *)&connect_addr,sizeof(connect_addr)) == -1)
    {
        error_handing("connect() error");
    }
    
    //步骤3：进行通讯
    if (write(client_sock,"nihao",sizeof("nihao")) == -1)
    {
        error_handing("write() error");
    }
    char buffer[30];
    if (read(client_sock,buffer,30) ==  -1)
    {
        error_handing("read() error");
    }
    printf("Receive message is %s\n",buffer);
    while (1)
    {
        /* code */
    }
    
    //步骤4：关闭连接
    close(client_sock);
    return 0;
}
